#------------------------------------------------------------------------------
# Script for cleaning and destroying a sharepoint farm
# NB! This script will not run on it's own - it's part of deploy.ps1 
#------------------------------------------------------------------------------


Write-Host -foregroundcolor green "# Executing build..."

#TODO: add check to see if current security-context has correct privileges

# ----------------------------------------------------
# Step 1.
# Create Index directory
#
Write-Host -foregroundcolor yellow "# 1. Creating index directory--------------------"

if ($CreateIndexDirectory)
{
  if (!(Test-Path $IndexLocation))
  {
    Write-Host -foregroundcolor yellow ("# Creating index directory '" + $IndexLocation + "'")
    ExecuteCommand "[void] (New-Item -type directory $IndexLocation)"
  }
  else 
  {
    Write-Host -foregroundcolor yellow ("# '" + $IndexLocation + "' already exists")
  }
}
else
{
  Write-Host -foregroundcolor yellow ("# $" + "CreateIndexDirectory=false, skipping")
}
# ----------------------------------------------------


# ----------------------------------------------------
# Step 2.
# Create Farm
#
echo ""
Write-Host -foregroundcolor yellow "# 2. Creating the Farm----------------------------"
if ($CreateFarm) 
{
  ExecuteCommand "& psconfig -cmd configdb -create -server ""$LocalDBServer"" -database ""$ConfigDB"" -user ""$FarmAdminAccount"" -password ""$FarmAdminPassword"" -admincontentdatabase ""$AdminContentDB""" $true
} 
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "CreateFarm=false, skipping")
}

# ----------------------------------------------------


# ----------------------------------------------------
# Step 3.
echo ""
Write-Host -foregroundcolor yellow "# 3. Provision Central Admin Application----------"

if ($ProvisionCentralAdmin) 
{
  ExecuteCommand "& psconfig -cmd adminvs -provision -port ""$AdminPort"" -windowsauthprovider onlyusentlm" $true
} 
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "ProvisionCentralAdmin=false, skipping")
}

# ----------------------------------------------------



# ----------------------------------------------------
# Step 4.
echo ""
Write-Host -foregroundcolor yellow "# 4. Install all Services-------------------------"

if ($InstallServices) 
{
  ExecuteCommand "& psconfig -cmd services install" $true
} 
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "InstallServices=false, skipping")
}

# ----------------------------------------------------




# ----------------------------------------------------
# Step 5.
echo ""
Write-Host -foregroundcolor yellow "# 5. Securing File System and Registry Keys-------"

if ($SecureFSandReg) 
{
  ExecuteCommand "& psconfig -cmd secureresources"
} 
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "SecureFSandReg=false, skipping")
}

# ----------------------------------------------------




# ----------------------------------------------------
# Step 6.
echo ""
Write-Host -foregroundcolor yellow "# 6. Update DB settings---------------------------"

if ($UpdateDBSettings) 
{
  foreach( $user in ($SearchSvcAccount, $CrawlAccount, $SspServiceAccount))
  {
    foreach( $db in ($ConfigDB, $AdminContentDB))
    {
      ExecuteCommand "& sqlcmd -S $LocalDBServer -d $db -Q ""CREATE USER [$user] FOR LOGIN [$user]""" $true
      ExecuteCommand "& sqlcmd -S $LocalDBServer -d $db -Q ""sp_addrolemember N'WSS_Content_Application_Pools', N'$user'""" $true
    }
  }
} 
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "UpdateDBSettings=false, skipping")
}



# ----------------------------------------------------
# Step 7.
echo ""
Write-Host -foregroundcolor yellow "# 7. Starting MOSS Search-------------------------"

if ($StartMOSSSearch) 
{
  ExecuteCommand "& stsadm -o osearch -action start -role IndexQuery -farmcontactemail ""$email"" -farmperformancelevel maximum -farmserviceaccount ""$SearchSvcAccount"" -farmservicepassword ""$SearchSvcPassword""" $true
} 
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "StartMOSSSearch=false, skipping")
}

# ----------------------------------------------------



# ----------------------------------------------------
# Step 8.
echo ""
Write-Host -foregroundcolor yellow "# 8. Starting WSS Search--------------------------"

if ($StartWSSSearch) 
{
  ExecuteCommand "& stsadm -o spsearch -action start -farmserviceaccount ""$SearchSvcAccount"" -farmservicepassword ""$SearchSvcPassword"" -farmcontentaccessaccount ""$CrawlAccount"" -farmcontentaccesspassword ""$CrawlPassword"" -databaseserver ""$LocalDBServer"" -databasename ""$WSSSearchDB""" $true
} 
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "StartWSSSearch=false, skipping")
}

# ----------------------------------------------------



# ----------------------------------------------------
# Step 9.
echo ""
Write-Host -foregroundcolor yellow "# 9. Installing all Config Features---------------"

if ($InstallAllConfigFeatures) 
{
  ExecuteCommand "& psconfig -cmd installfeatures" $true
} 
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "InstallAllConfigFeatures=false, skipping")
}

# ----------------------------------------------------


# ----------------------------------------------------
# Step 10.
echo ""
Write-Host -foregroundcolor yellow "# 10. Installing Global Solutions-----------------"
if ($InstallGlobalSolutions) 
{
  foreach ($solution in $GlobalSolutions)
  {
    Write-Host -foregroundcolor yellow "# Installing(add+deploy) $solution"
    ExecuteCommand "& stsadm -o addsolution -filename ""..\wsp\$solution"""
    ExecuteCommand "& stsadm -o deploysolution -name ""$solution"" -immediate -force -allowGacDeployment -allowCasPolicies"
  }
  Write-Host -foregroundcolor yellow "# Executing timer jobs"
  ExecuteCommand "& stsadm -o execadmsvcjobs"
}
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "InstallGlobalSolutions=false, skipping")
}
# ----------------------------------------------------


# ----------------------------------------------------
# Step 11.
echo ""
Write-Host -foregroundcolor yellow "# 11. Creating My Sites Web Application-----------"
if ($CreateMySiteWebApp) 
{
  ExecuteCommand "& stsadm -o extendvs -url ""$MySite_URL"" -donotcreatesite -exclusivelyusentlm -ownerlogin ""$userAndDomainName"" -owneremail ""$email"" -databaseserver $LocalDBServer -databasename ""$MySiteDB"" -description ""$MySite_Description"" -sethostheader -apidname ""$MySite_AppPool"" -apidtype configurableid -apidlogin ""$SspAppPoolAccount"" -apidpwd ""$SspAppPoolPassword""" $true
}
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "CreateMySiteWebApp=false, skipping")
}
# ----------------------------------------------------



# ----------------------------------------------------
# Step 12.
echo ""
Write-Host -foregroundcolor yellow "# 12. Creating SSP Web Application----------------"
if ($CreateSSPWebApp) 
{
  ExecuteCommand "& stsadm -o extendvs -url ""$SSP_URL"" -donotcreatesite -exclusivelyusentlm -databaseserver $LocalDBServer -databasename ""$SharedServicesDB"" -description ""$SSP_Description"" -sethostheader -apidname ""$MySite_AppPool"" -apidtype configurableid -apidlogin ""$SspAppPoolAccount"" -apidpwd ""$SspAppPoolPassword""" $true

  Write-Host -foregroundcolor yellow "# Resetting IIS"
  ExecuteCommand "& iisreset"
}
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "CreateSSPWebApp=false, skipping")
}
# ----------------------------------------------------



# ----------------------------------------------------
# Step 13.
echo ""
Write-Host -foregroundcolor yellow "# 13. Creating SSP Site---------------------------"
if ($CreateSSPSite) 
{
  ExecuteCommand "& stsadm -o createssp -title ""$ssp_Title"" -url ""$SSP_URL"" -mysiteurl ""$MySite_URL"" -ssplogin ""$SspServiceAccount"" -indexserver ""$LocalDBServer"" -indexlocation ""$IndexLocation"" -ssppassword ""$SspServicePassword"" -sspdatabaseserver ""$LocalDBServer"" -sspdatabasename ""$SharedServicesContentDB"" -searchdatabaseserver ""$LocalDBServer"" -searchdatabasename ""$SharedServicesSearchDB"" -ssl no" $true
}
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "CreateSSPSite=false, skipping")
}
# ----------------------------------------------------





# ----------------------------------------------------
# Step 14. 
echo ""
Write-Host -foregroundcolor yellow "# 14. Creating Team Web Application----"
if ($CreateTeamWebApp) 
{
	#TODO: parameter "-exclusivelyusentlm" must be configurable

  if ($ContentAccount -eq "NetworkService")
  {
    ExecuteCommand "& stsadm -o extendvs -url ""$Team_URL"" -donotcreatesite -ownerlogin ""$userAndDomainName"" -owneremail ""$email"" -exclusivelyusentlm -databaseserver ""$LocalDBServer"" -databasename ""$TeamContentDB"" -description ""$Team_Description"" -sethostheader -apidname ""$SharePoint_AppPool"" -apidtype NetworkService" $true
  }
  else
  {
    ExecuteCommand "& stsadm -o extendvs -url ""$Team_URL"" -donotcreatesite -ownerlogin ""$userAndDomainName"" -owneremail ""$email"" -exclusivelyusentlm -databaseserver ""$LocalDBServer"" -databasename ""$TeamContentDB"" -description ""$Team_Description"" -sethostheader -apidname ""$SharePoint_AppPool"" -apidtype configurableid -apidlogin ""$ContentAccount"" -apidpwd ""$ContentPassword""" $true
  }

    Write-Host -foregroundcolor yellow "# Resetting IIS"
    ExecuteCommand "& iisreset"
}
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "CreateTeamWebApp=false, skipping")
}
# ----------------------------------------------------


# ----------------------------------------------------
# Step 16.
echo ""
Write-Host -foregroundcolor yellow "# 16. Creating info portal"
if ($CreateInfoWebApp) 
{
    if ($RestoreInfoDatabase) 
    {
      Write-Host -foregroundcolor yellow "# Restoring info database"
      ExecuteCommand "& stsadm -o extendvs -url ""$Info_URL"" -donotcreatesite -ownerlogin ""$userAndDomainName"" -owneremail ""$email"" -exclusivelyusentlm -databaseserver ""$CommonDBServer"" -databasename ""$InfoContentDB"" -description ""$Info_Description"" -sethostheader -apidname ""$SharePoint_AppPool"" -apidtype configurableid -apidlogin ""$ContentAccount"" -apidpwd ""$ContentPassword""" $true
    }
    else # Create a new database since there is none to attach
    {
      Write-Host -foregroundcolor yellow "# Creating new info database"
      ExecuteCommand "& stsadm -o extendvs -url ""$Info_URL"" -ownerlogin ""$userAndDomainName"" -owneremail ""$email"" -exclusivelyusentlm  -databasename ""$InfoContentDB"" -description ""$Info_Description"" -sethostheader -apidname ""$SharePoint_AppPool"" -apidtype configurableid -apidlogin ""$ContentAccount"" -apidpwd ""$ContentPassword"" -sitetemplate ""CMSPUBLISHING#0""" $true
    }

    Write-Host -foregroundcolor yellow "# Resetting IIS"
    ExecuteCommand "& iisreset"
}
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "CreateInfoWebApp=false, skipping")
}
# ----------------------------------------------------


# ----------------------------------------------------
# Step 17.
echo ""
Write-Host -foregroundcolor yellow "# 17. Installing Web application Solutions----------"
if ($InstallWebApplicationSolutions) 
{

  foreach( $solution in $WebApplicationsSolutions)
  {
    Write-Host -foregroundcolor yellow "# Installing solution ..\wsp\$solution"
    ExecuteCommand "& stsadm -o addsolution -filename ""..\wsp\$solution"""

    # TODO: consider extending this to accept a parameter array with contenturls instead of using -allcontenturls param
    Write-Host -foregroundcolor yellow "# Deploying $solution to allcontenturls"
    ExecuteCommand "& stsadm -o deploysolution -name ""$solution"" -immediate -force -allowGacDeployment -allcontenturls -allowCasPolicies"
  }
  
  Write-Host -foregroundcolor yellow "# Executing timer jobs"
  ExecuteCommand "& stsadm -o execadmsvcjobs"
  
  Write-Host -foregroundcolor yellow "# Resetting IIS"
  ExecuteCommand "& iisreset"
  
  Write-Host -foregroundcolor yellow "# Restarting Windows SharePoint Services Timer"
  ExecuteCommand "& net stop ""Windows SharePoint Services Timer"""
  ExecuteCommand "& net start ""Windows SharePoint Services Timer"""
}
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "InstallWebApplicationSolutions=false, skipping")
}
# ----------------------------------------------------




# ----------------------------------------------------
# Step 18.
echo ""
Write-Host -foregroundcolor yellow "# 18. Configure Email settings--------------------"
if ($ConfigureEmail) 
{
  ExecuteCommand "& stsadm -o email -outsmtpserver ""$SMTPServer"" -fromaddress ""$EmailFromAddress"" -replytoaddress ""$email"" -codepage 65001" $true
}
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "ConfigureEmail=false, skipping")
}
# ----------------------------------------------------


# ----------------------------------------------------
# Step 19.
echo ""
Write-Host -foregroundcolor yellow "# 19. Create MySite Site--------------------------"
if ($CreateMySite) 
{
    #TODO
}
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "CreateMySite=false, skipping")
}
# ----------------------------------------------------


# ----------------------------------------------------
# Step 20.
echo ""
Write-Host -foregroundcolor yellow "# 20. Create root web for Team portal----------"
if ($CreateTeamSiteCollection) 
{
  $TeamSiteTitle = "Team Portal title"
  $TeamSiteDescription = "Team Portal description"
  $TeamSiteTemplate = "STS#0"

  ExecuteCommand "& stsadm -o createsite -url ""$Team_URL"" -ownerlogin ""$userAndDomainName"" -owneremail ""$email"" -sitetemplate ""$TeamSiteTemplate"" -title ""$TeamSiteTitle"" -description ""$TeamSiteDescription""" $true
}
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "CreateTeamSiteCollection=false, skipping")
}
# ----------------------------------------------------


# ----------------------------------------------------
# Step 20a.
echo ""
Write-Host -foregroundcolor yellow "# 20a. Create Team subsites-------------------"
if ($CreateTeamSubSites)
{
  $TeamSubSiteTemplate = "STS#1"

  foreach( $site in $TeamSubSites)
  {
		Write-Host -foregroundcolor yellow "# Creating subsite $Team_URL/$site.."
		ExecuteCommand "& stsadm -o createweb -url ""$Team_URL/$site"" -sitetemplate ""$TeamSubSiteTemplate"" -title ""$site""" $true
  }
}
else 
{
	Write-Host -foregroundcolor yellow ("# $" + "CreateTeamSubSites=false, skipping")
}
# ----------------------------------------------------


# ----------------------------------------------------
# Step 20b.
echo ""
Write-Host -foregroundcolor yellow "# 20b. Add managed path for meetings----------------"
if ($AddMeetingsManagedPath)
{
	ExecuteCommand "& stsadm -o addpath -url ""$Team_URL/meetings"" -type wildcardinclusion" $true
}
else 
{
	Write-Host -foregroundcolor yellow ("# $" + "AddMeetingsManagedPath=false, skipping")
}
# ----------------------------------------------------


# ----------------------------------------------------
# Step 20c.
echo ""
Write-Host -foregroundcolor yellow "# 20c. Create Meetings site collection----------------"
if ($CreateMeetingsSiteCollections)
{
	$MeetingsSiteCollectionTemplate = "STS#2"
	foreach( $site in $TeamMeetingsSites)
	{
		Write-Host -foregroundcolor yellow "# Creating site collection $Team_URL/meetings/$site.."
		ExecuteCommand "& stsadm -o createsite -url ""$Team_URL/meetings/$site"" -owneremail ""$email"" -sitetemplate ""$MeetingsSiteCollectionTemplate"" -title ""$site"" -ownerlogin ""$FarmAdminAccount""" $true
	}
}
else 
{
	Write-Host -foregroundcolor yellow ("# $" + "CreateMeetingsSiteCollections=false, skipping")
}
# ----------------------------------------------------


# ----------------------------------------------------
# Step 20d.
echo ""
Write-Host -foregroundcolor yellow "# 20d. Create COA stuff----------------"
if ($CreateCOAStuff)
{
	Write-Host -foregroundcolor yellow "# Creating $Team_URL/sites/coa..."
	ExecuteCommand "& stsadm -o createsite -url ""$Team_URL/sites/coa"" -owneremail ""$email""  -sitetemplate ""STS#2"" -title ""COA"" -ownerlogin ""$FarmAdminAccount""" $true

	Write-Host -foregroundcolor yellow "# Creating $Team_URL/sites/coa/cases..."
	ExecuteCommand "& stsadm -o createweb -url ""$Team_URL/sites/coa/cases"" -sitetemplate ""STS#1"" -title ""Cases""" $true 
}
else 
{
	Write-Host -foregroundcolor yellow ("# $" + "CreateCOAStuff=false, skipping")
}
# ----------------------------------------------------


# ----------------------------------------------------
# Step 21.
echo ""
Write-Host -foregroundcolor yellow "# 21. Setting Recycle Bin Settings----------------"
if ($SetRecycleBinSettings) 
{
  foreach( $url in ($Info_URL, $Team_URL, $MySite_URL))
  {
    ExecuteCommand "& stsadm -o setproperty -pn recycle-bin-enabled -pv yes -url ""$url"""
    ExecuteCommand "& stsadm -o setproperty -pn recycle-bin-retention-period -pv 30 -url ""$url"""
    ExecuteCommand "& stsadm -o setproperty -pn second-stage-recycle-bin-quota -pv 20 -url ""$url"""
  }
}
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "SetRecycleBinSettings=false, skipping")
}
# ----------------------------------------------------


# ----------------------------------------------------
# Step 22.
echo ""
Write-Host -foregroundcolor yellow "# 22. Setting Maximum Upload File Size------------"
if ($SetMaxUploadFileSize) 
{
  foreach( $url in ($Info_URL, $Team_URL, $MySite_URL))
  {
    ExecuteCommand "& stsadm -o setproperty -pn max-file-post-size -pv 50 -url ""$url"""
  }
}
else 
{
  echo ("$" + "SetMaxUploadFileSize=false, skipping")
}
# ----------------------------------------------------



# ----------------------------------------------------
# Step 23.
echo ""
Write-Host -foregroundcolor yellow "# 23. Enable Self Service Site Management---------"
if ($EnableSelfService) 
{
  ExecuteCommand "& stsadm -o enablessc -url ""$MySite_URL"""
}
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "EnableSelfService=false, skipping")
}
# ----------------------------------------------------



# ----------------------------------------------------
# Step 25.
echo ""
Write-Host -foregroundcolor yellow "# 25. Add users to Farm Administrators group------"
if ($AddFarmAdministrators) 
{
  # Add the Content AppPool account
  
  ExecuteCommand "& stsadm -o adduser -url ""http://${env:COMPUTERNAME}:{$AdminPort}"" -userlogin ""$ContentAccount"" -group ""Farm Administrators"" -username ""$ContentAccount"" -useremail ""content.${env:COMPUTERNAME}@mydomain.com""" $true
}
else 
{
  Write-Host -foregroundcolor yellow ("# $" + "AddFarmAdministrators=false, skipping")
}
# ----------------------------------------------------




# ----------------------------------------------------
# Step 26.
echo ""
Write-Host -foregroundcolor yellow "# 26. Create Projects members group ----------------"
if ($CreateProjectMembersGroup)
{
	#TODO
}
else 
{
	Write-Host -foregroundcolor yellow ("# $" + "CreateProjectMembersGroup=false, skipping")
}
# ----------------------------------------------------



# ----------------------------------------------------
# Step 99.
echo ""
Write-Host -foregroundcolor green "# Build finished."
# ----------------------------------------------------
